package com.xiezhr.ollomadsdemo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * @author xiezhr
 * url: www.xiezhrspace.cn
 * @version 1.0
 * @description: TODO
 * @date 2025/2/18 22:11
 */
//@RestController
//@RequestMapping("/ai")
//public class DeepSeekController {
//
//    private final ChatClient chatclient;
//
//    // 构造方法，用于构造chatclient 实列
//    public DeepSeekController(ChatClient.Builder chatClientBuilder){
//        this.chatclient =chatClientBuilder.build();
//    }
//
//
//    @GetMapping("/chat")
//    public ResponseEntity<Flux<String>> chat(@RequestParam(value="message")String message){
//    try{
//        //调用ChatClient生成响应，并以Flux<String>（响应流）形式返回
//        Flux<String>response =chatclient.prompt(message).stream().content();
//        return ResponseEntity.ok(response);
//    }catch(Exception e){
//        return ResponseEntity.badRequest().build();
//    }
//    }
//}

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class DeepSeekController {
    private static final Logger logger = LoggerFactory.getLogger(DeepSeekController.class);

    private final ChatClient chatclient;

    public DeepSeekController(ChatClient.Builder chatClientBuilder) {
        this.chatclient = chatClientBuilder.build();
    }

    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
    public ResponseEntity<Flux<String>> chat(@RequestParam(value="message") String message) {
        try {
            Flux<String> response = chatclient.prompt(message).stream().content();
            // 打印响应数据
            response.subscribe(data -> logger.info("Response data: {}", data));
            return ResponseEntity.ok()
                    .contentType(MediaType.TEXT_EVENT_STREAM) // 设置内容类型为文本事件流
                    .header(HttpHeaders.CONTENT_ENCODING, "utf-8") // 设置字符编码
                    .body(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}